#!/usr/bin/env python

# Copyright (c) 2013 The Chromium Embedded Framework Authors.
# Portions copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# This script is wrapper for CEF/Chromium that adds some support for how GYP
# is invoked by Chromium beyond what can be done in the gclient hooks.

from file_util import *
from gclient_util import *
import glob
import os
import shlex
import subprocess
import sys

# The JCEF root directory is the parent directory of _this_ script.
jcef_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))

# Test the operating system.
platform = '';
if sys.platform == 'win32':
  platform = 'windows'
elif sys.platform == 'darwin':
  platform = 'macosx'
elif sys.platform.startswith('linux'):
  platform = 'linux'

sys.path.insert(0, os.path.join(jcef_dir, 'third_party', 'gyp', 'pylib'))
import gyp

# On Windows, Psyco shortens warm runs of build/gyp_chromium by about
# 20 seconds on a z600 machine with 12 GB of RAM, from 90 down to 70
# seconds.  Conversely, memory usage of build/gyp_chromium with Psyco
# maxes out at about 158 MB vs. 132 MB without it.
#
# Psyco uses native libraries, so we need to load a different
# installation depending on which OS we are running under. It has not
# been tested whether using Psyco on our Mac and Linux builds is worth
# it (the GYP running time is a lot shorter, so the JIT startup cost
# may not be worth it).
if sys.platform == 'win32':
  try:
    sys.path.insert(0, os.path.join(jcef_dir, 'third_party', 'psyco_win32'))
    import psyco
  except:
    psyco = None
else:
  psyco = None

def apply_gyp_environment(file_path=None):
  """
  Reads in a *.gyp_env file and applies the valid keys to os.environ.
  """
  if not file_path or not os.path.exists(file_path):
    return
  file_contents = open(file_path).read()
  try:
    file_data = eval(file_contents, {'__builtins__': None}, None)
  except SyntaxError, e:
    e.filename = os.path.abspath(file_path)
    raise
  supported_vars = ( 'CHROMIUM_GYP_SYNTAX_CHECK',
                     'GYP_DEFINES',
                     'GYP_GENERATOR_FLAGS',
                     'GYP_GENERATOR_OUTPUT', )
  for var in supported_vars:
    val = file_data.get(var)
    if val:
      if var in os.environ:
        print 'INFO: Environment value for "%s" overrides value in %s.' % (
            var, os.path.abspath(file_path)
        )
      else:
        os.environ[var] = val

def additional_include_files(args=[]):
  """
  Returns a list of additional (.gypi) files to include, without
  duplicating ones that are already specified on the command line.
  """
  # Determine the include files specified on the command line.
  # This doesn't cover all the different option formats you can use,
  # but it's mainly intended to avoid duplicating flags on the automatic
  # makefile regeneration which only uses this format.
  specified_includes = set()
  for arg in args:
    if arg.startswith('-I') and len(arg) > 2:
      specified_includes.add(os.path.realpath(arg[2:]))

  result = []
  def AddInclude(path):
    if os.path.realpath(path) not in specified_includes:
      result.append(path)

  # Always include common.gypi.
  AddInclude(os.path.join(jcef_dir, 'build', 'common.gypi'))

  return result

if __name__ == '__main__':
  args = sys.argv[1:]

  # Use the Psyco JIT if available.
  if psyco:
    psyco.profile()
    print "Enabled Psyco JIT."

  if 'SKIP_CHROMIUM_GYP_ENV' not in os.environ:
    # Update the environment based on jcef.gyp_env
    gyp_env_path = os.path.join(os.path.dirname(jcef_dir), 'jcef.gyp_env')
    apply_gyp_environment(gyp_env_path)

  args.extend(['-I' + i for i in additional_include_files(args)])

  # There shouldn't be a circular dependency relationship between .gyp files,
  # but in Chromium's .gyp files, on non-Mac platforms, circular relationships
  # currently exist.  The check for circular dependencies is currently
  # bypassed on other platforms, but is left enabled on the Mac, where a
  # violation of the rule causes Xcode to misbehave badly.
  # TODO(mark): Find and kill remaining circular dependencies, and remove this
  # option.  http://crbug.com/35878.
  # TODO(tc): Fix circular dependencies in ChromiumOS then add linux2 to the
  # list.
  if sys.platform not in ('darwin',):
    args.append('--no-circular-check')

  # If CHROMIUM_GYP_SYNTAX_CHECK is set to 1, it will invoke gyp with --check
  # to enfore syntax checking.
  syntax_check = os.environ.get('CHROMIUM_GYP_SYNTAX_CHECK')
  if syntax_check and int(syntax_check):
    args.append('--check')

  print "\nGenerating JCEF version header file..."
  gyper = [ 'python', 'tools/make_version_header.py',
            '--header', 'native/jcef_version.h' ]
  RunAction(jcef_dir, gyper)

  print 'Updating projects from gyp files...'
  sys.stdout.flush()

  # Off we go...
  result = gyp.main(args);

  if result == 0:
    if platform == 'windows':
      # Fix .vcproj and .vcxproj files.
      files = []
      for file in get_files(os.path.join(jcef_dir, '*.vcproj')):
        files.append(file)
      for file in get_files(os.path.join(jcef_dir, '*.vcxproj')):
        files.append(file)
      for file in files:
        data = read_file(file)
        # Fix xcopy arguments.
        data = data.replace('xcopy \\', 'xcopy /')
        write_file(file, data)
    elif platform == 'linux':
      # Fix .mk files.
      files = []
      for file in get_files(os.path.join(jcef_dir, '*.mk')):
        files.append(file)
      for file in files:
        data = read_file(file)
        # Drop lib.target from the output path.
        data = data.replace('/lib.target', '')
        write_file(file, data)
    elif platform == 'macosx':
      # Fix Xcode project files.
      files = [
        os.path.join(jcef_dir, 'jcef.xcodeproj/project.pbxproj'),
        os.path.join(jcef_dir, 'third_party/cef/macosx64/cefclient.xcodeproj/project.pbxproj'),
      ]
      for file in files:
        data = read_file(file)
        # Fix file paths.
        data = data.replace('build/mac/', 'third_party/cef/macosx64/tools/')
        # Fix framework type.
        data = data.replace('lastKnownFileType = text; name = "Chromium Embedded Framework";', \
                            'explicitFileType = "compiled.mach-o.dylib"; name = "Chromium Embedded Framework";')
        # Fix target compiler.
        data = data.replace('GCC_VERSION = 4.2;', 'GCC_VERSION = com.apple.compilers.llvm.clang.1_0;')
        write_file(file, data)

  sys.exit(result)
